package com.heima.wemedia.gateway.filter;

import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Order
public class AuthorizationFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        //判断是否是访问登录接口,是 -> 放行
        String path = request.getURI().getPath();
        if (path.contains("login_auth")) {
            return chain.filter(exchange);
        }
        //不是登录操作，判断是否有token
        //没有token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)) {
            //响应未登录，拦截
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //有token，对token进行合法性判断
        try {
            AppJwtUtil.getClaimsBody(token);
        } catch (Exception e) {
            e.printStackTrace();
            //响应未登录，拦截
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }
}
